package com.ccbooks.bo;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;

import com.ccbooks.dao.BooksDao;
import com.ccbooks.dao.DBHelper;
import com.ccbooks.util.BooksEngine;
import com.ccbooks.util.PDB.BooksEnginePDB;
import com.ccbooks.view.BookContentView;
import com.ccbooks.vo.CatelogItem;

public class BookMarkBo {

	private Context context;
	public static List<CatelogItem> marks;
	private BooksDao dao;
	
	public BookMarkBo(Context context){
		this.context=context;
		dao = BooksDao.getDao(context);
	}

	/*
	 * 本方法通过配对文件实现该功能，现已不采用； //读取书签内容; public List<CatelogItem> readMarks(String
	 * bookPath){ String markPath=FileBo.getFileRealname(bookPath);
	 * BufferedReader br=null; FileReader read=null; try { DateFormat format1 =
	 * new SimpleDateFormat("yyyy-MM-dd"); read = new
	 * FileReader(markPath+".mark"); br = new BufferedReader(read); String
	 * row=null; if((row=br.readLine())!=null && row.equals("###start###")){
	 * marks=new ArrayList<CatelogItem>(); CatelogItem catelogItem=null;
	 * while((row=br.readLine())!=null){ catelogItem=new CatelogItem();
	 * catelogItem
	 * .pageIndex=Integer.parseInt(row.substring(0,row.indexOf('#')));
	 * catelogItem.title=row.substring(row.indexOf('#')+1, row.indexOf('@'));
	 * catelogItem.date=format1.parse(row.substring(row.indexOf('@')));
	 * marks.add(catelogItem); } } } catch (FileNotFoundException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } catch (IOException e) {
	 * // TODO Auto-generated catch block e.printStackTrace(); }
	 * catch(NumberFormatException e){ e.printStackTrace(); }catch
	 * (ParseException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); }finally{ try { br.close(); read.close(); } catch
	 * (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
	 * } } return marks; }
	 * 
	 * //加入书签; public void addBookMark(int pageIndex,String title,String
	 * bookPath){ CatelogItem catelogItem =new CatelogItem();
	 * catelogItem.title=title; catelogItem.pageIndex=pageIndex;
	 * catelogItem.date=new Date(); marks=readMarks(bookPath); if(marks==null){
	 * marks=new ArrayList<CatelogItem>(); } marks.add(catelogItem); String
	 * markstr=getMarkStr(marks); try { writeMarks(bookPath, markstr); } catch
	 * (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
	 * } }
	 * 
	 * //删除书签 public void delBookMark(int pageIndex,String bookPath){
	 * marks=readMarks(bookPath); if(marks!=null){ for(int
	 * i=0;i<marks.size();i++){ if(marks.get(i).pageIndex==pageIndex){
	 * marks.remove(i); break; } } String markstr=getMarkStr(marks); try {
	 * writeMarks(bookPath, markstr); } catch (IOException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } } }
	 * 
	 * //写入书签文件： private void writeMarks(String bookPath,String markstr) throws
	 * IOException{ FileWriter fw=null; String
	 * markPath=FileBo.getFileRealname(bookPath); fw=new
	 * FileWriter(markPath+".mark"); fw.write(markstr); fw.flush(); fw.close();
	 * 
	 * }
	 * 
	 * //获得数据 private String getMarkStr(List<CatelogItem> list){
	 * Collections.sort(list); StringBuffer sb=new StringBuffer("###start###");
	 * for(CatelogItem item:list){ sb.append('\n'); sb.append(item.pageIndex);
	 * sb.append('#'); sb.append(item.title); sb.append('@');
	 * sb.append(item.date);
	 * 
	 * } return new String(sb); }
	 */

	// 通过数据库实现标签功能
	// 读取书签;
	public List<CatelogItem> readMarksByDb(int bookid) {
		
		Cursor cursor=null;
		marks = new ArrayList<CatelogItem>();
		CatelogItem item = null;
		try{
			cursor = dao.select(true,DBHelper.TABLE_MARKS,null,"bookid=?",new String[]{String.valueOf(bookid)},CatelogItem.PageIndex,null);
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				item = new CatelogItem();
				item.id = cursor.getInt(0);
				item.bookid = cursor.getInt(cursor
						.getColumnIndexOrThrow(CatelogItem.BOOK_ID));
				item.pageIndex = cursor.getInt(cursor
						.getColumnIndexOrThrow(CatelogItem.PageIndex));
				item.title = cursor.getString(cursor
						.getColumnIndexOrThrow(CatelogItem.TITLE));
				item.date = cursor.getInt(cursor
						.getColumnIndexOrThrow(CatelogItem.DATE));
				marks.add(item);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			try{
				cursor.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		return marks;
	}

	//加入书签;
	public void addMarksByDb(int bookid,int pageIndex,String title){

		ContentValues cv = new ContentValues();
		cv.put(CatelogItem.PageIndex, pageIndex);
		cv.put(CatelogItem.BOOK_ID, bookid);
		cv.put(CatelogItem.TITLE,title);
		cv.put(CatelogItem.DATE, new Date().getTime());
		try{
			this.dao.insert(DBHelper.TABLE_MARKS, cv);
		}catch(SQLException e){
			e.printStackTrace();
		}
		marks=readMarksByDb(bookid);
	}
	
	//删除书签
	public void delMarkByDb(int bookid,int id){
		try {
			dao.delete(DBHelper.TABLE_MARKS, id);
		} catch (SQLException e) {
			// TODO: handle exception
		}
		marks=readMarksByDb(bookid);
	}
	
	/**查看是否书签的页面*/
	public static void isMark(BookContentView bcv){
		bcv.mark = null;
		BooksDao dao = null;
		/*Cursor cursor = dao.select(true, DBHelper.TABLE_MARKS, null,
				"page1>=? and page<=?", new String[] {
						String.valueOf(BooksEngine.markPoint),
						String.valueOf(BooksEngine.pageEndPoint) },
				"page", "0,1");*/
		Cursor cursor = null;
		try {
			dao = BooksDao.getDao(bcv);
			String sql = null;
			if(FileBo.BOOKTYPE_TXT.equals(bcv.book.booktype)){
				sql = "select * from ccb_marks where bookid="+bcv.book.id+" and page>="
				+ BooksEngine.markPoint + " and page<"
				+ BooksEngine.pageEndPoint + " order by page limit 0,1";
			}else if(FileBo.BOOKTYPE_PDB.equals(bcv.book.booktype)){		
				sql = "select * from ccb_marks where bookid="+bcv.book.id+" and page>="
				+ BooksEnginePDB.markPoint + " and page<"
				+ BooksEnginePDB.pageEndPoint + " order by page limit 0,1";	
			}else if(FileBo.BOOKTYPE_CHM.equals(bcv.book.booktype)){
				
			}else if(FileBo.BOOKTYPE_HTML.equals(bcv.book.booktype)){
				
			}else if(FileBo.BOOKTYPE_PDF.equals(bcv.book.booktype)){
			
			}
			
			cursor = dao.exec(sql);

			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
					.moveToNext()) {
				bcv.mark = new CatelogItem();
				bcv.mark.id = cursor.getInt(0);
				bcv.mark.pageIndex = cursor.getInt(cursor
						.getColumnIndexOrThrow(CatelogItem.PageIndex));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try{
				cursor.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
